from logging import exception

from rest_framework import serializers
from rest_framework import exceptions
from apps.oaauth.models import OAUser, UserStatusChoices, OADepartment

#登录输入验证
class LoginSerializer(serializers.Serializer):
    email = serializers.EmailField(required=True)
    password = serializers.CharField(max_length=20, min_length=6)

    def validate(self, attrs):
        email = attrs.get('email')
        password = attrs.get('password')
        if email and password:
            user = OAUser.objects.filter(email=email).first()
            if not user:
                raise serializers.ValidationError('请传入正确的邮箱')
            if not user.check_password(password):
                raise serializers.ValidationError('请传入正确的密码')
            if user.status == UserStatusChoices.UNACTIVATED:
                raise serializers.ValidationError('该用户尚未激活')
            elif user.status == UserStatusChoices.LOCKED:
                raise serializers.ValidationError('该用户已被锁定，请联系管理员')
            attrs['user'] = user
            return attrs
        else:
            raise serializers.ValidationError('请传入邮箱和密码')


class DepartmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = OADepartment
        fields = '__all__'

#返回部分user信息
class UserSerializer(serializers.ModelSerializer):
    department = DepartmentSerializer()
    class Meta:
        model = OAUser
        exclude = ('password', 'groups', 'user_permissions')

#重设密码验证
class ResetPwdSerializer(serializers.Serializer):
    old_pwd = serializers.CharField(max_length=20, min_length=6)
    pwd1 = serializers.CharField(max_length=20, min_length=6)
    pwd2 = serializers.CharField(max_length=20, min_length=6)

    def validate(self, attrs):
        old_pwd = attrs.get('old_pwd')
        pwd1 = attrs.get('pwd1')
        pwd2 = attrs.get('pwd2')

        user = self.context['request'].user
        if not user.check_password(old_pwd):
            raise exceptions.ValidationError("旧密码错误")
        if pwd1 != pwd2:
            raise exceptions.ValidationError("两个新密码不一致")
        return attrs

